<template>
  <div class="course-selection">
    <el-card class="box-card">
      <template #header>
        <div class="card-header">
          <span>学生选课</span>
          <!-- 调试信息 -->
          <div style="font-size: 12px; color: #999;">
            权限状态: {{ debugPermissions }}
          </div>
        </div>
      </template>

      <el-tabs v-model="activeTab" @tab-click="handleTabClick">
        <!-- 可选课程 -->
        <el-tab-pane label="可选课程" name="available">
          <div class="course-list">
            <el-row :gutter="20">
              <el-col :span="24" v-if="availableCourses.length === 0">
                <el-empty description="暂无可选课程"></el-empty>
              </el-col>
              <el-col :span="12" v-for="course in availableCourses" :key="course.courseApplicationId">
                <el-card class="course-card" :class="{ 'not-selectable': !course.canSelect }" shadow="hover">
                  <div class="course-info">
                    <h3 class="course-name">{{ course.courseName }}</h3>
                    <div class="course-details">
                      <p><strong>任课教师：</strong>{{ course.teacherName }}</p>
                      <p><strong>学年学期：</strong>{{ course.academicYear }} {{ course.semester }}</p>
                      <p><strong>课程学时：</strong>{{ course.courseHours }}学时</p>
                      <p><strong>选课人数：</strong>{{ course.currentStudents }}/{{ course.maxStudents }}</p>
                    </div>
                    <div class="course-actions">
                      <el-button
                        v-if="!course.isSelected && course.canSelect"
                        type="primary"
                        @click="handleSelectCourse(course)"
                        :disabled="course.currentStudents >= course.maxStudents"
                      >
                        {{ course.currentStudents >= course.maxStudents ? '已满员' : '选课' }}
                      </el-button>
                      <el-button
                        v-else-if="!course.isSelected && !course.canSelect"
                        type="info"
                        disabled
                      >
                        不可选择
                      </el-button>
                      <el-button
                        v-else-if="course.isSelected"
                        type="success"
                        disabled
                      >
                        已选择
                      </el-button>
                    </div>
                  </div>
                </el-card>
              </el-col>
            </el-row>
          </div>
        </el-tab-pane>

        <!-- 已选课程 -->
        <el-tab-pane label="已选课程" name="selected">
          <div class="selected-courses">
            <el-table :data="selectedCourses" style="width: 100%">
              <el-table-column prop="courseName" label="课程名称" width="200"></el-table-column>
              <el-table-column prop="teacherName" label="任课教师" width="120"></el-table-column>
              <el-table-column prop="academicYear" label="学年" width="120"></el-table-column>
              <el-table-column prop="semester" label="学期" width="100"></el-table-column>
              <el-table-column prop="courseHours" label="学时" width="80"></el-table-column>
              <el-table-column prop="selectionTime" label="选课时间" width="180">
                <template #default="scope">
                  {{ formatDateTime(scope.row.selectionTime) }}
                </template>
              </el-table-column>
              <el-table-column label="操作" width="120">
                <template #default="scope">
                  <el-button 
                    type="danger" 
                    size="small" 
                    @click="handleDropCourse(scope.row)"
                  >
                    退课
                  </el-button>
                </template>
              </el-table-column>
            </el-table>
          </div>
        </el-tab-pane>
      </el-tabs>
    </el-card>
  </div>
</template>

<script>
import { getCurrentStudentAvailableCourses, getCurrentStudentSelectedCourses, selectCourseForCurrentStudent, dropCourseForCurrentStudent } from '@/api/courseSelection'
import { usePermissions } from '@/stores/permission'

export default {
  name: 'CourseSelection',
  setup() {
    const { hasPermission, getUserPermissions } = usePermissions()
    
    return {
      hasPermission,
      getUserPermissions
    }
  },
  data() {
    return {
      activeTab: 'available',
      availableCourses: [],
      selectedCourses: []
    }
  },
  computed: {
    debugPermissions() {
      const permissions = this.getUserPermissions()
      return `权限数量: ${permissions.length}, 包含选课权限: ${permissions.includes('course-selection:view-available')}`
    }
  },
  mounted() {
    this.loadAvailableCourses()
    this.loadSelectedCourses()

    // 调试权限信息
    console.log('当前用户权限:', this.getUserPermissions())
    console.log('是否有查看可选课程权限:', this.hasPermission('course-selection:view-available'))
  },
  methods: {
    
    handleTabClick(tab) {
      if (tab.name === 'available') {
        this.loadAvailableCourses()
      } else if (tab.name === 'selected') {
        this.loadSelectedCourses()
      }
    },
    
    async loadAvailableCourses() {
      try {
        const response = await getCurrentStudentAvailableCourses()
        this.availableCourses = response.data || []
        console.log('加载可选课程成功:', this.availableCourses.length)
      } catch (error) {
        this.$message.error('加载可选课程失败')
        console.error('加载可选课程失败:', error)
      }
    },

    async loadSelectedCourses() {
      try {
        const response = await getCurrentStudentSelectedCourses()
        this.selectedCourses = response.data || []
        console.log('加载已选课程成功:', this.selectedCourses.length)
      } catch (error) {
        this.$message.error('加载已选课程失败')
        console.error('加载已选课程失败:', error)
      }
    },
    
    async handleSelectCourse(course) {
      try {
        // 检查是否可以选择该课程
        if (!course.canSelect) {
          this.$message.warning('您只能选择本学院本专业本班级教师开设的课程，且学年学期必须匹配')
          return
        }

        await this.$confirm('确认选择该课程吗？', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        })

        await selectCourseForCurrentStudent({
          courseApplicationId: course.courseApplicationId
        })

        this.$message.success('选课成功')
        // 刷新可选课程列表和已选课程列表
        this.loadAvailableCourses()
        this.loadSelectedCourses()
      } catch (error) {
        if (error !== 'cancel') {
          this.$message.error(error.message || '选课失败')
        }
      }
    },

    async handleDropCourse(course) {
      try {
        await this.$confirm('确认退选该课程吗？', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        })

        await dropCourseForCurrentStudent(course.courseApplicationId)

        this.$message.success('退课成功')
        this.loadSelectedCourses()
        this.loadAvailableCourses()
      } catch (error) {
        if (error !== 'cancel') {
          this.$message.error(error.message || '退课失败')
        }
      }
    },
    
    formatDateTime(dateTime) {
      if (!dateTime) return ''
      return new Date(dateTime).toLocaleString('zh-CN')
    }
  }
}
</script>

<style scoped>
.course-selection {
  padding: 20px;
}

.course-list {
  margin-top: 20px;
}

.course-card {
  margin-bottom: 20px;
  transition: all 0.3s ease;
}

.course-card:hover {
  transform: translateY(-2px);
}

.course-card.not-selectable {
  opacity: 0.6;
  background-color: #f5f5f5;
}

.course-card.not-selectable .course-name {
  color: #999;
}

.course-card.not-selectable .course-details {
  color: #666;
}

.course-info {
  padding: 10px;
}

.course-name {
  margin: 0 0 15px 0;
  font-size: 18px;
  font-weight: bold;
  color: #303133;
}

.course-details {
  margin-bottom: 15px;
}

.course-details p {
  margin: 8px 0;
  font-size: 14px;
  color: #606266;
}

.course-actions {
  text-align: right;
}

.selected-courses {
  margin-top: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}
</style>